<?php
/**
 * 公司/门店账号模型
 */

namespace app\badmin\model;


use app\badmin\model\LoginLog;
use app\common\controller\BadminController;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Log;
use custom\Redis;
use custom\Token;
use think\Db;
use think\Exception;

class CompanyAccount extends BaseModel {

    /**
     * 登录
     * @param $params
     * @return array|bool
     * @throws \think\Exception
     */
    public static function checkLogin($params) {
        if (!preg_match('/^1[3-9]\d{9}$/', $params['phone'])) {
            Err::add('手机号格式不正确', RespCode::PARAMS_ERR);
            return false;
        }
        $data = Db::name('company_account')->where('deleted', 0)->getByphone($params['phone']);
        if (empty($data)) {
            Err::add('账号或密码错误', RespCode::PARAMS_ERR);
            return false;
        }
        if (md5($params['password']) != $data['password']) {
            Err::add('账号或密码错误', RespCode::PARAMS_ERR);
            return false;
        }
        $token = new Token();
        $token_string = $token->getToken($data['id'], [], Token::BADMIN_TOKEN, Token::EXPIRE_TIME, RedisKey::BADMIN_TOKEN_HASH);

        if ($data['company_shop_id'] == 0) {//公司账号，返公司默认城市
            $company = Company::getOne([['id', '=', $data['company_id']]], 'default_city_code');
            $default_city_code = explode('-', $company['default_city_code']);
            $city_code = $default_city_code[0];
            $city_name = $default_city_code[1];
        } else {
            //门店账号，返门店默认城市
            $companyShop = CompanyShop::getOne([['id', '=', $data['company_shop_id']]], 'city_code');
            $default_city_code = explode('-', $companyShop['city_code']);
            $city_code = $default_city_code[0];
            $city_name = $default_city_code[1];
        }

        //公司账号
        if ($data['company_shop_id'] == 0) {
            $tabeName = 'company';
            $field = 'company_id';
        } else {
            $tabeName = 'company_shop';
            $field = 'company_shop_id';
        }
        $admin_name = Db::name($tabeName)->getFieldByid($data[$field], 'name');

        $saveLog = [
            'company_id'      => (int)$data['company_id'],
            'company_shop_id' => (int)$data['company_shop_id'],
            'admin_name'      => (string)$admin_name,
            'title'           => (string)'登录',
            'ip'              => (string)request()->ip(),
            'itime'           => (string)time(),
        ];
        try{
            if(!LoginLog::saveLoginLog($saveLog)){
                throw new Exception('登录日志写入失败');
            }
        }catch (Exception $e){
            $err = "异常信息:{$e->getMessage()} | 异常所在的代码行:{$e->getLine()} | 异常文件{$e->getFile()} | php 版本 " . PHP_VERSION . "(" . PHP_OS . ")";
            Log::write($err, "saveLoginLog.log");
        }

        $result = [
            'token'     => $token_string,
            'phone'     => $data['phone'],
            'city_code' => $city_code,
            'city_name' => $city_name,
        ];
        return $result;
    }

    /**
     * 获取单条数据
     * @param $map
     * @param $column
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getOne($map, $column) {
        return self::where($map)->field($column)->find();
    }

    /**
     * 获取公司剩余可添加经纪人数
     * @param $id
     * @return array|\PDOStatement|string|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCompanyLaveNum($id) {
        return self::alias('ca')
            ->join("company c", 'c.id = ca.company_id')
            ->where('ca.company_id', $id)
            ->field('c.lave_num')
            ->find();
    }

    /**
     * 删除
     * @param $id
     * @return int|string
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public static function del($params) {
        return self::where('company_shop_id', $params['id'])
            ->where('company_id', $params['company_id'])
            ->update(['deleted' => 1]);
    }

    /**
     * 修改密码
     * @param $params
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public static function editPwd($params) {
        $data = Db::name('company_account')
            ->where('deleted', 0)
            ->where('company_id', $params['company_id'])
            ->where('company_shop_id', $params['company_shop_id'])
            ->find();
        if (empty($data)) {
            Err::add('账号不存在', RespCode::PARAMS_ERR);
            return false;
        }
        if (!preg_match('/^\w{6,15}$/', trim($params['oldpwd']))) {
            Err::add('密码：6-15位字母大小写数字下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (!preg_match('/^\w{6,15}$/', trim($params['newPwd']))) {
            Err::add('密码：6-15位字母大小写数字下划线', RespCode::PARAMS_ERR);
            return false;
        }
        if (trim($params['newPwd']) != trim($params['againPwd'])) {
            Err::add('两次密码输入不一致', RespCode::PARAMS_ERR);
            return false;
        }
        if ($data['password'] != md5($params['oldpwd'])) {
            Err::add('原始密码错误', RespCode::PARAMS_ERR);
            return false;
        }
        $pwd = md5(trim($params['againPwd']));
        self::where('company_id', $params['company_id'])
            ->where('company_shop_id', $params['company_shop_id'])
            ->update(['password' => $pwd]);
        $redisModel = Redis::getInstance();
        $Token = new Token();
        $redisModel->hdel(RedisKey::BADMIN_TOKEN_HASH . '_' . $Token::BADMIN_TOKEN, $params['user_id']);
        return true;
    }

    /**
     * 退出
     * @param $headers
     * @param $uInfo
     * @return bool
     */
    public static function quit($headers, $uInfo) {
        //公司账号
        if ($uInfo['company_shop_id'] == 0) {
            $tabeName = 'company';
            $field = 'company_id';
        } else {
            $tabeName = 'company_shop';
            $field = 'company_shop_id';
        }
        $admin_name = Db::name($tabeName)->getFieldByid($uInfo[$field], 'name');
        $saveLog = [
            'company_id'      => (int)$uInfo['company_id'],
            'company_shop_id' => (int)$uInfo['company_shop_id'],
            'admin_name'      => (string)$admin_name,
            'title'           => (string)'退出',
            'ip'              => (string)request()->ip(),
            'itime'           => (string)time(),
        ];
        try{
            if(!LoginLog::saveLoginLog($saveLog)){
                throw new Exception('退出日志写入失败');
            }
        }catch (Exception $e){
            $err = "异常信息:{$e->getMessage()} | 异常所在的代码行:{$e->getLine()} | 异常文件{$e->getFile()} | php 版本 " . PHP_VERSION . "(" . PHP_OS . ")";
            Log::write($err, "saveLoginLog.log");
        }
        $str = substr(base64_decode(substr($headers['token'], 32), true), 32);
        $redisKey = RedisKey::BADMIN_TOKEN_HASH . '_' . Token::BADMIN_TOKEN;
        $redisModel = Redis::getInstance();
        if (!$redisModel->hDel($redisKey, $str)) {
            Err::add('请稍后重试', RespCode::PARAMS_ERR);
            return false;
        }
        return true;
    }

}
